package com.bank.aop;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.bank.pojo.BankAdmin;
import com.bank.pojo.BankMgrLog;
import com.bank.svc.BankAdminSvc;
import com.bank.svc.MgrLogSvc;

@Component
@Aspect
public class BankLogger {
	private static Map<String,String> classNames=new HashMap<String,String>();
	private static Map<String,String> methodNames=new HashMap<String,String>();
	
	static{
		classNames.put("BankCardSvc", "银行卡");
		classNames.put("BankNewsSvc", "新闻");
		classNames.put("BankUserSvc", "账户");
		
		methodNames.put("addCard","办卡");
		methodNames.put("addNews","新增新闻");
		methodNames.put("delNews","删除新闻");
		methodNames.put("updateNews","修改新闻");
		methodNames.put("addUser","开户");
	}
	
	@Resource(name="mgrLogSvc")
	private MgrLogSvc mls;
	@Resource(name="bankAdminSvc")
	private BankAdminSvc bas;
	
	@Pointcut("execution(* com.bank.svc..*.*(..))")
	private void anyMethod(){}
	
	@AfterReturning(pointcut="anyMethod()",returning="result")
	public void doAfterRetruning(JoinPoint join,Object result){  
		String className=join.getTarget().getClass().getName();
		className=className.split("\\.")[3];
		String methodName=join.getSignature().getName();
		String mgrClass="";String mgrMethod="";int targetResult;
		for(String cn:classNames.keySet()){
			if(cn.equals(className)){
				mgrClass=classNames.get(cn);
				break;
			}
		}
		
		for(String mn:methodNames.keySet()){
			if(mn.equals(methodName)){
				mgrMethod=methodNames.get(mn);
				break;
			}
		}
		
		if(Boolean.parseBoolean(result.toString())){
			targetResult=0;
		}else{
			targetResult=1;
		}
		if(!mgrClass.equals("")&&!mgrMethod.equals("")){
			BankAdmin admin=bas.getAdminById(1);
			BankMgrLog log=new BankMgrLog(admin, mgrClass, mgrMethod, targetResult,new Timestamp(new Date().getTime()));
			mls.addLog(log);
		}
	}

	public void setMls(MgrLogSvc mls) {
		this.mls = mls;
	}

	public void setBas(BankAdminSvc bas) {
		this.bas = bas;
	}
}